package cli;
/**
 * Read the logging file location and name from the settings xml file
 * and writes a log message to the file
 * If the file doesnt exist it will be created
 * Log messages are in the form of : category, message
 * Adding a message to the log file is done as follows: Logging.Log( cat, message )
 * 
 * @author Peter
 *
 */


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

/**
 * Add a  log message to the log file <br/>
 * Log file location / name is in the settings.xml file
 * @author Peter
 *
 */
public class Logging {
	
	private static Logging instance = null;
	private static String logFile = null; 
	
	private Logging() {
		logFile = Settings.getLogFile();
	}
	
	/**
	 * Add a message to the log
	 * @param cat category
	 * @param message to be added
	 */
	public static void log( String cat, String message ) {
		if ( instance == null) {
			instance = new Logging();
		}
		
		writeIntoLog( cat, message);
	}
	
	private static void writeIntoLog( String cat, String msg) {
		if ( logFile == null ) {
			System.out.println("No Log file found");
			return;
		}
		
		SimpleDateFormat ft =  new SimpleDateFormat (Settings.DATE_FORMAT );
		String lineText = ft.format( new Date() ) + " | " + cat + " | " + msg + "\n";
		
		//create the file if not exist
		File f = new File(logFile);
		Boolean append;
		if (! f.exists() ) {
			append = false;
		} else
			append = true;
		
		BufferedWriter bufferedWriter = null;

		try {
			//Construct the BufferedWriter object
			bufferedWriter = new BufferedWriter(new FileWriter(f, append));

			//Start writing to the output stream
			bufferedWriter.write(lineText);
		

		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			//Close the BufferedWriter
			try {
				if (bufferedWriter != null) {
					bufferedWriter.flush();
					bufferedWriter.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

}
